package com.zcw.rabbitmq.workqueue;

import com.rabbitmq.client.Channel;
import com.zcw.rabbitmq.util.RabbitConnectionUtil;

import java.io.IOException;
import java.util.Random;

public class WorkProducer {

    public static void getProducer(){
        Channel channel = RabbitConnectionUtil.getRabbitConnection();

        String queueName = RabbitConnectionUtil.getQueueName();

        try {
            channel.queueDeclare(queueName,false,false,false,null);

            while (true){
                String message = generateRandomString(20);
                channel.basicPublish("", queueName,false,null,message.getBytes());
                Thread.sleep(1000);
                System.out.println("发送消息：" + message + "成功");
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public static String generateRandomString(int length) {
        // 定义一个字符数组，包含大写字母、小写字母和数字
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
        StringBuilder sb = new StringBuilder(length);

        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 随机选择一个字符并添加到StringBuilder中
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }

        return sb.toString();
    }
}
